package com.digitalchina.lxnsy.adapter;

import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.apkfuns.logutils.LogUtils;
import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.api.BusinessFarmSystem;
import com.digitalchina.lxnsy.entity.CartVO;
import com.digitalchina.lxnsy.interfaces.ICallBack;
import com.digitalchina.lxnsy.toolkit.FrescoUtil;
import com.digitalchina.lxnsy.toolkit.StringUtil;
import com.facebook.drawee.view.SimpleDraweeView;

import java.util.List;

/**
 * ================================================
 * 项目名称：BigData
 * 类描述：购物车Adapter
 * 包名：com.digitalchina.bigdata.adapter
 * 创建人：白彦东
 * 创建时间：2016/12/30 15:16
 * 修改备注：
 * ================================================
 */

public class CartAdapter extends BaseExpandableListAdapter {

    protected ICallBack iCallBack;//回调接口类

    protected Context mContext;
    protected LayoutInflater layoutInflater;
    private List<CartVO> groupList;
    private List<List<CartVO.ShoppingCartItemVOListBean>> childList;
    private int mGroupPosition, mChildPosition;
    private String itemID; // 商品编号 删除成功后remove
    boolean isDelete = false;

    OnAllCheckedBoxNeedChangeListener onAllCheckedBoxNeedChangeListener;

    public void setOnAllCheckedBoxNeedChangeListener(OnAllCheckedBoxNeedChangeListener onAllCheckedBoxNeedChangeListener) {
        this.onAllCheckedBoxNeedChangeListener = onAllCheckedBoxNeedChangeListener;
    }

    public CartAdapter(ICallBack iCallBack, Context mContext, List<CartVO> groupList, List<List<CartVO.ShoppingCartItemVOListBean>> childList) {
        this.iCallBack = iCallBack;
        this.mContext = mContext;
        this.groupList = groupList;
        this.childList = childList;
        layoutInflater = LayoutInflater.from(mContext);
    }


    public boolean isDelete() {
        return isDelete;
    }

    public void setDelete(boolean delete) {
        isDelete = delete;
    }

    /**
     * 移除已经删除的商品项
     */
    private void removeDeleteItem() {
        if (!StringUtil.isStrEmpty(itemID)) {
            LogUtils.e(itemID);
            for (int i = 0; i < groupList.size(); i++) {
                for (int j = 0; j < childList.get(i).size(); j++) {
                    if (childList.get(i).get(j).getShoppingCartItemId().equals(itemID)) {
                        childList.get(i).remove(j);
                    }
                }
                if (groupList.get(i).getShoppingCartItemVOList().size() < 1) {
                    groupList.remove(i);
                    i--;
                }
            }

            childList.clear();

            for (int i = 0; i < groupList.size(); i++) {
                List<CartVO.ShoppingCartItemVOListBean> shoppingCartItemVOListBeen = groupList.get(i).getShoppingCartItemVOList();
                childList.add(shoppingCartItemVOListBeen);
            }

            setListData(groupList, childList);
        }
    }

    public void setListData(List<CartVO> groupList, List<List<CartVO.ShoppingCartItemVOListBean>> childList) {
        this.groupList = groupList;
        this.childList = childList;
        notifyDataSetChanged();
    }

    @Override
    public int getGroupCount() {
        return groupList.size();
    }

    @Override
    public int getChildrenCount(int groupPosition) {
        return childList.get(groupPosition).size();
    }

    @Override
    public Object getGroup(int groupPosition) {
        return groupList.get(groupPosition);
    }

    @Override
    public Object getChild(int groupPosition, int childPosition) {
        return childList.get(groupPosition).get(childPosition);
    }

    @Override
    public long getGroupId(int groupPosition) {
        return groupPosition;
    }

    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }

    @Override
    public boolean hasStableIds() {
        return true;
    }

    @Override
    public View getGroupView(final int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
        final ViewHolderGroup viewHolderGroup;
        if (convertView == null) {
            convertView = inflate(R.layout.item_cart_group, parent);
            viewHolderGroup = new ViewHolderGroup();
            viewHolderGroup.mRootLayout = (RelativeLayout) convertView.findViewById(R.id.item_cart_group_root_layout);
            viewHolderGroup.cbGroup = (CheckBox) convertView.findViewById(R.id.item_cart_group_checkbox);
            viewHolderGroup.sdvStoreLogo = (SimpleDraweeView) convertView.findViewById(R.id.item_cart_group_iv_store_logo);
            viewHolderGroup.tvStoreName = (TextView) convertView.findViewById(R.id.item_cart_group_tv_store_name);
            convertView.setTag(viewHolderGroup);
        } else
            viewHolderGroup = (ViewHolderGroup) convertView.getTag();

        // 商店LOGO
        FrescoUtil.showImageSmall(groupList.get(groupPosition).getSupplierLogo(), viewHolderGroup.sdvStoreLogo);
        // 商店名称
        viewHolderGroup.tvStoreName.setText(groupList.get(groupPosition).getSupplierName());

        if (groupList.get(groupPosition).isCheck()) {
            viewHolderGroup.cbGroup.setChecked(true);
        } else {
            viewHolderGroup.cbGroup.setChecked(false);
        }

        // 父容器的checkbox监听
        viewHolderGroup.cbGroup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                groupList.get(groupPosition).setCheck(viewHolderGroup.cbGroup.isChecked());
                for (int i = 0; i < childList.get(groupPosition).size(); i++) {
                    childList.get(groupPosition).get(i).setCheck(viewHolderGroup.cbGroup.isChecked());
                }
                iCallBack.clickOk();
                notifyDataSetChanged();

                //控制总checkedbox 接口
//                onAllCheckedBoxNeedChangeListener.onCheckedBoxNeedChange(dealAllParentIsChecked());

            }
        });

//        viewHolderGroup.mRootLayout.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                GotoUtil.gotoActivity((Activity) mContext, MerchantActivity.class, "merchantId", groupList.get(groupPosition).getSupplierId());
//            }
//        });
        return convertView;
    }

    @Override
    public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
        final ViewHolderChild viewHolderChild;
        if (convertView == null) {
            convertView = inflate(R.layout.item_cart_child, parent);
            viewHolderChild = new ViewHolderChild();
            viewHolderChild.cbChild = (CheckBox) convertView.findViewById(R.id.item_cart_child_checkbox);
            viewHolderChild.tvInvalid = (TextView) convertView.findViewById(R.id.item_cart_child_tv_invalid);
            viewHolderChild.sdvImage = (SimpleDraweeView) convertView.findViewById(R.id.item_cart_child_iv_images);
            viewHolderChild.tvTitle = (TextView) convertView.findViewById(R.id.item_cart_child_tv_title);
            viewHolderChild.tvIntroduce = (TextView) convertView.findViewById(R.id.item_cart_child_tv_introduce);
            viewHolderChild.tvPrice = (TextView) convertView.findViewById(R.id.item_cart_child_tv_price);
            viewHolderChild.tvNum = (TextView) convertView.findViewById(R.id.item_cart_child_tv_num);
            viewHolderChild.llparent = (LinearLayout) convertView.findViewById(R.id.item_cart_child_parent_layout);
            viewHolderChild.llEdit = (LinearLayout) convertView.findViewById(R.id.item_cart_child_layout_edit);

            viewHolderChild.tvNumEdit = (TextView) convertView.findViewById(R.id.item_cart_child_tv_num_edit);
            viewHolderChild.ivMinus = (ImageView) convertView.findViewById(R.id.item_cart_child_iv_minus);
            viewHolderChild.ivPlus = (ImageView) convertView.findViewById(R.id.item_cart_child_iv_plus);
            convertView.setTag(viewHolderChild);
        } else
            viewHolderChild = (ViewHolderChild) convertView.getTag();

        if (childList.get(groupPosition).get(childPosition).getStatus().equals("1")) {
            viewHolderChild.tvInvalid.setVisibility(View.GONE);
            viewHolderChild.cbChild.setVisibility(View.VISIBLE);
        } else {
            viewHolderChild.tvInvalid.setVisibility(View.VISIBLE);
            viewHolderChild.cbChild.setVisibility(View.GONE);
        }

        if (isDelete) {
            viewHolderChild.llEdit.setVisibility(View.VISIBLE);
            viewHolderChild.tvNum.setVisibility(View.GONE);
        } else {
            viewHolderChild.llEdit.setVisibility(View.GONE);
            viewHolderChild.tvNum.setVisibility(View.VISIBLE);
        }

        // 商品编辑数量
        viewHolderChild.tvNumEdit.setText(childList.get(groupPosition).get(childPosition).getItemQuantity());


        // 商品图片
        FrescoUtil.showImageSmall(childList.get(groupPosition).get(childPosition).getItemLogo(), viewHolderChild.sdvImage);
        // 商品名称
        viewHolderChild.tvTitle.setText(childList.get(groupPosition).get(childPosition).getItemName());
        // 商品属性
//        viewHolderChild.tvIntroduce.setText(childList.get(groupPosition).get(childPosition).getItemSummary());
        viewHolderChild.tvIntroduce.setText(StringUtil.isStrEmpty(childList.get(groupPosition).get(childPosition).getAttrName()) ? "商品属性：无" : "商品属性：" + childList.get(groupPosition).get(childPosition).getAttrName());
        // 商品价格
        viewHolderChild.tvPrice.setText(String.format("￥ %s", childList.get(groupPosition).get(childPosition).getItemPrice()));
        // 商品数量
        viewHolderChild.tvNum.setText("x " + childList.get(groupPosition).get(childPosition).getItemQuantity());

        // 子容器的checkbox监听
        viewHolderChild.cbChild.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                childList.get(groupPosition).get(childPosition).setCheck(viewHolderChild.cbChild.isChecked());

                boolean isGroupCheck = true;
                for (int i = 0; i < childList.get(groupPosition).size(); i++) {
                    // 判断如果里面有一个为未选中 则父选择器同步
                    if (!childList.get(groupPosition).get(i).isCheck()) {
                        isGroupCheck = false;
                        break;
                    }
                }
                groupList.get(groupPosition).setCheck(isGroupCheck);
                iCallBack.clickOk();
                notifyDataSetChanged();

                //控制总checkedbox 接口
//                onAllCheckedBoxNeedChangeListener.onCheckedBoxNeedChange(dealAllParentIsChecked());
            }
        });


        viewHolderChild.cbChild.setChecked(childList.get(groupPosition).get(childPosition).isCheck());


        // 减法
        viewHolderChild.ivMinus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Integer.parseInt(childList.get(groupPosition).get(childPosition).getItemQuantity()) == 1)
                    return;

                childList.get(groupPosition).get(childPosition).setItemQuantity(String.valueOf(Integer.parseInt(childList.get(groupPosition).get(childPosition).getItemQuantity()) - 1));
                notifyDataSetChanged();

                BusinessFarmSystem.setShoppingCartItemQuantities((Activity) mContext, childList.get(groupPosition).get(childPosition).getShoppingCartItemId(), childList.get(groupPosition).get(childPosition).getItemQuantity(), new Handler());
            }
        });

        // 加法
        viewHolderChild.ivPlus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                childList.get(groupPosition).get(childPosition).setItemQuantity(String.valueOf(Integer.parseInt(childList.get(groupPosition).get(childPosition).getItemQuantity()) + 1));
                notifyDataSetChanged();

                BusinessFarmSystem.setShoppingCartItemQuantities((Activity) mContext, childList.get(groupPosition).get(childPosition).getShoppingCartItemId(), childList.get(groupPosition).get(childPosition).getItemQuantity(), new Handler());
            }
        });


        /**
         * 根布局点击事件
         */
//        viewHolderChild.llparent.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                GotoUtil.gotoActivity((Activity) mContext, DataDetailActivity.class, "productId", childList.get(groupPosition).get(childPosition).getItemId());
//            }
//        });


        return convertView;
    }

    public boolean dealAllParentIsChecked() {
        if (groupList == null || groupList.size() <= 0)
            return false;

        for (int i = 0; i < groupList.size(); i++) {
            if (!groupList.get(i).isCheck()) {
                return false;//如果有一个没选择  就false
            }
        }
        return true;
    }

    public interface OnAllCheckedBoxNeedChangeListener {
        void onCheckedBoxNeedChange(boolean allParentIsChecked);
    }

    @Override
    public boolean isChildSelectable(int i, int i1) {
        return false;
    }

    public View inflate(int layoutId, ViewGroup parent) {
        return layoutInflater.inflate(layoutId, parent, false);
    }

    public class ViewHolderGroup {
        RelativeLayout mRootLayout;
        CheckBox cbGroup;
        SimpleDraweeView sdvStoreLogo;
        TextView tvStoreName;
    }

    public class ViewHolderChild {
        CheckBox cbChild;
        TextView tvInvalid;
        SimpleDraweeView sdvImage; // 商品图片
        TextView tvTitle; // 商品名称
        TextView tvIntroduce; // 商品简介
        TextView tvPrice; // 商品价格
        TextView tvNum; // 商品数量
        LinearLayout llparent; // 根布局
        LinearLayout llEdit; // 编辑布局

        TextView tvNumEdit; // 商品编辑数量
        ImageView ivMinus; // 减号
        ImageView ivPlus; // 加号

    }
}
